#import <Foundation/Foundation.h>
#import "HomeViewController.h"
#import "ImageProcessing.h"
#import "Cache.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "GPUImage.h"
#import "JXButton.h"
#import "AppDelegate.h"

@implementation ImageProcessing

- (void)viewDidLoad{
    self.navigationItem.title = @"图片浏览";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.imageScroll = [[UIScrollView alloc]init];
    self.imageScroll.backgroundColor = [UIColor whiteColor];
    self.imageScroll.userInteractionEnabled = YES;
    
    self.contentView = [UIView new];
    self.contentView.userInteractionEnabled = YES;
    [self.imageScroll addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.imageScroll);
        make.height.mas_equalTo(130);
        make.width.mas_equalTo(5*100);
    }];

    [self.view addSubview:self.imageScroll];
    UIEdgeInsets padding = UIEdgeInsetsMake(150, 0, 80, 0);
    [self.imageScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
        make.height.mas_equalTo(130);
        make.left.right.equalTo(self.view);
    }];
    [self getFilterImg];
    
    //self.img = [[UIImage imageNamed:@"1.jpg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.imgView = [[UIImageView alloc]initWithImage:self.img];
    self.imgView.backgroundColor = [UIColor whiteColor];
    self.imgView.contentMode = UIViewContentModeScaleAspectFit;
    padding = UIEdgeInsetsMake(100, 0, 0, 0);
    [self.view addSubview:self.imgView];
    [self.imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).with.offset(-100);
        make.height.mas_equalTo(500);
        make.width.mas_equalTo(self.view.mas_width);
    }];
    
    self.contrast = [[UISlider alloc]init];
    self.contrast.minimumValue = 0.5;// 设置最小值
    self.contrast.maximumValue = 5;// 设置最大值
    self.contrast.value = 2;// 设置初始值
    self.contrast.continuous = YES;// 设置可连续变化
    [self.contrast addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.contrast];
    [self.contrast mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.imgView.mas_bottom).with.offset(25);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(self.view.mas_width).with.offset(-100);
    }];
    
    
    self.save = [[UIButton alloc]init];
    //self.save.backgroundColor = [UIColor colorWithRed:22/255.0 green:219/255.0 blue:39/255.0 alpha:1];
    [self.save setTitle:@"保存" forState:(UIControlStateNormal)];
    self.save.titleLabel.font = [UIFont systemFontOfSize: 20];
    [self.save setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.save.layer.masksToBounds = YES;
    [self.save addTarget:self action:@selector(saveToAlbum) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.save];
    padding = UIEdgeInsetsMake(10, 10, 0, 10);
    [self.save mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageScroll.mas_bottom).with.offset(padding.top);
        make.right.equalTo(self.view.mas_right).with.offset(-padding.right);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    
    self.cancel = [[UIButton alloc]init];
    [self.cancel setTitle:@"取消" forState:(UIControlStateNormal)];
    self.cancel.titleLabel.font = [UIFont systemFontOfSize: 20];
    [self.cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.cancel.layer.masksToBounds = YES;
    [self.cancel addTarget:self action:@selector(returnToAlbum) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.cancel];
    padding = UIEdgeInsetsMake(10, 10, 0, 10);
    [self.cancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageScroll.mas_bottom).with.offset(padding.top);
        make.left.equalTo(self.view.mas_left).with.offset(padding.left);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    
    self.publish = [[UIButton alloc]init];
    [self.publish setTitle:@"发布" forState:(UIControlStateNormal)];
    self.publish.titleLabel.font = [UIFont systemFontOfSize: 20];
    [self.publish setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.publish.layer.masksToBounds = YES;
    [self.publish addTarget:self action:@selector(publishToGround) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.publish];
    padding = UIEdgeInsetsMake(50, 10, 0, 10);
    [self.publish mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(padding.top);
        make.right.equalTo(self.view.mas_right).with.offset(-padding.right);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
}

- (instancetype)init:(UIImage*)img
{
    self = [super init];
    if (self) {
        self.img = img;
    }
    return self;
}

- (void)getFilterImg{
    self.fitBtnArr = [[NSMutableArray alloc]init];
    self.fitImgArr =  [[NSMutableArray alloc]init];
    NSArray *filTypes = [[NSArray alloc]initWithObjects:@"colourize",@"mask",@"anime",@"wave",@"scream", nil];
    //self.fitImgArr = [NSMutableArray arrayWithCapacity:10];
    for(int i = 0; i < 5; i++){
        JXButton *fitlerBtn = [[JXButton alloc] initWithFrame:CGRectMake(i*100, 10, 80, 80)];
        //fitlerBtn.backgroundColor = [UIColor redColor];
        [fitlerBtn setTitle:[filTypes objectAtIndex:i]  forState:0];
        [fitlerBtn setImage:self.img forState:0];
        [fitlerBtn setTitleColor:[UIColor blackColor] forState:0];
        fitlerBtn.layer.cornerRadius = 10;
        fitlerBtn.layer.masksToBounds = YES;
        [self.contentView addSubview:fitlerBtn];
        [self.fitBtnArr addObject: fitlerBtn];
        [self.fitImgArr addObject:self.img];
    }
    
//    [self.fitImgArr replaceObjectAtIndex:1 withObject:self.img];
//    NSLog(@"%@", [self.fitImgArr objectAtIndex:1]);
    
    // 原图像转base64编码
    NSData *data = UIImageJPEGRepresentation(self.img, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    NSString *access_token = @"24.f0412e128c64978e508b80973dedb36c.2592000.1612457390.282335-23490150";
    int fitIndex;
    NSString *URLString;
    NSDictionary *parameters;
    AFHTTPSessionManager *manager;
    
    // 上色
    fitIndex = 0;
    URLString = [NSString stringWithFormat:@"https://aip.baidubce.com/rest/2.0/image-process/v1/colourize?access_token=%@", access_token];
    parameters = @{
        @"image": encodedImageStr,
    };
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            NSLog(@"0 %@", responseObject);
            if([[responseObject allKeys] containsObject:@"image"]){
                NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:responseObject[@"image"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
                [self.fitImgArr replaceObjectAtIndex:fitIndex withObject:decodedImage];
                [[self.fitBtnArr objectAtIndex:fitIndex] setImage:decodedImage forState: 0];
            }
            [[self.fitBtnArr objectAtIndex:fitIndex] addTarget:self action:@selector(onClickFitBtn0) forControlEvents:(UIControlEventTouchUpInside)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];

    // 图像风格动漫戴口罩
    fitIndex = 1;
    URLString = [NSString stringWithFormat:@"https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=%@", access_token];
    parameters = @{
        @"image": encodedImageStr,
        @"type": @"anime_mask",
        @"mask_id": @5
    };
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            if([[responseObject allKeys] containsObject:@"image"]){
                NSLog(@"1 %@", responseObject);
                NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:responseObject[@"image"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
                [self.fitImgArr replaceObjectAtIndex:fitIndex withObject:decodedImage];
                [[self.fitBtnArr objectAtIndex:fitIndex] setImage:decodedImage forState: 0];
            }
            [[self.fitBtnArr objectAtIndex:fitIndex] addTarget:self action:@selector(onClickFitBtn1) forControlEvents:(UIControlEventTouchUpInside)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];
    
    // 动漫画
    fitIndex = 2;
    URLString = [NSString stringWithFormat:@"https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=%@", access_token];
    parameters = @{
        @"image": encodedImageStr,
        @"type": @"anime_mask"
    };
    [[self.fitBtnArr objectAtIndex:fitIndex] addTarget:self action:@selector(onClickFitBtn2) forControlEvents:(UIControlEventTouchUpInside)];
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            if([[responseObject allKeys] containsObject:@"image"]){
                NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:responseObject[@"image"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
                [self.fitImgArr replaceObjectAtIndex:fitIndex withObject:decodedImage];
                [[self.fitBtnArr objectAtIndex:fitIndex] setImage:decodedImage forState: 0];
            }
            [[self.fitBtnArr objectAtIndex:fitIndex] addTarget:self action:@selector(onClickFitBtn2) forControlEvents:(UIControlEventTouchUpInside)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];

    // 图像风格wave
    fitIndex = 3;
    URLString = [NSString stringWithFormat:@"https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=%@", access_token];
    parameters = @{
        @"image": encodedImageStr,
        @"option":@"wave"
    };
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            //NSLog(@"success %@", responseObject);
            if([[responseObject allKeys] containsObject:@"image"]){
                NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:responseObject[@"image"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
                [self.fitImgArr replaceObjectAtIndex:fitIndex withObject:decodedImage];
                [[self.fitBtnArr objectAtIndex:fitIndex] setImage:decodedImage forState: 0];
            }
            [[self.fitBtnArr objectAtIndex:fitIndex] addTarget:self action:@selector(onClickFitBtn3) forControlEvents:(UIControlEventTouchUpInside)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];

    // 图像风格scream
    fitIndex = 4;
    URLString = [NSString stringWithFormat:@"https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans?access_token=%@", access_token];
    parameters = @{
        @"image": encodedImageStr,
        @"option":@"scream"
    };
    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            //NSLog(@"success %@", responseObject);
            if([[responseObject allKeys] containsObject:@"image"]){
                NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:responseObject[@"image"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
                [self.fitImgArr replaceObjectAtIndex:fitIndex withObject:decodedImage];
                [[self.fitBtnArr objectAtIndex:fitIndex] setImage:decodedImage forState: 0];
            }
            [[self.fitBtnArr objectAtIndex:fitIndex] addTarget:self action:@selector(onClickFitBtn4) forControlEvents:(UIControlEventTouchUpInside)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];
}

- (void)onClickFitBtn0{
    self.img = [self.fitImgArr objectAtIndex:0];
    self.imgView.image = self.img;
}

- (void)onClickFitBtn1{
    self.img = [self.fitImgArr objectAtIndex:1];
    self.imgView.image = self.img;
}

- (void)onClickFitBtn2{
    self.img = [self.fitImgArr objectAtIndex:2];
    self.imgView.image = self.img;
}

- (void)onClickFitBtn3{
    self.img = [self.fitImgArr objectAtIndex:3];
    NSLog(@"click");
    self.imgView.image = self.img;
}

- (void)onClickFitBtn4{
    self.img = [self.fitImgArr objectAtIndex:4];
    self.imgView.image = self.img;
}

- (void)sliderValueChanged:(id)sender {
    UISlider *slider = (UISlider *)sender;
    GPUImageContrastFilter *filter = [[GPUImageContrastFilter alloc]init];
    filter.contrast = slider.value;
    [filter forceProcessingAtSize:self.img.size];
    GPUImagePicture *pic = [[GPUImagePicture alloc] initWithImage:self.img];
    [pic addTarget:filter];
    
    [pic processImage];
    [filter useNextFrameForImageCapture];
    self.imgView.image = [filter imageFromCurrentFramebuffer];
    //self.valueLabel.text = [NSString stringWithFormat:@"%.1f", slider.value];
}

- (void)saveToAlbum{
//    UIImage *img = [[UIImage imageNamed:@"3.jpg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImageWriteToSavedPhotosAlbum(self.img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)returnToAlbum{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)publishToGround{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    
    NSData *data = UIImageJPEGRepresentation(self.img, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@%@", @"http://47.107.247.52:8080/", myDelegate.userID, @"/uploadPicture"];
    NSDictionary *parameters = @{@"picture":encodedImageStr};
    NSDictionary *headers = @{@"token":myDelegate.token};
    
    [manager POST:URLString parameters:parameters headers:headers progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            if([responseObject[@"ok"] boolValue]){
                NSString *pictureURL = responseObject[@"data"];
                NSString *URLString = [NSString stringWithFormat:@"%@%@%@", @"http://47.107.247.52:8080/", myDelegate.userID, @"/createBlog"];
                NSDictionary *parameters = @{@"user_id":myDelegate.userID, @"content":@" ", @"picture":pictureURL};
                NSDictionary *headers = @{@"token":myDelegate.token};
                
                [manager POST:URLString parameters:parameters headers:headers progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发布成功" message:nil preferredStyle: UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [self dismissViewControllerAnimated:YES completion:nil];
                        UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
                        [((HomeViewController *)(((UINavigationController *)(((UITabBarController *)window.rootViewController).viewControllers.firstObject)).viewControllers[0])) reload];
                        }]];
                    [self presentViewController:alert animated:YES completion:^{
                    }];
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];
}

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error){
        msg = @"保存图片失败" ;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:msg message:nil preferredStyle: UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                return;
            }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        msg = @"保存图片成功" ;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:msg message:nil preferredStyle: UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                return;
            }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

@end
